import { getProfileInfo } from '@/api/profile'
import { loginAPI } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    username: '',
    profile: {}
  },
  mutations: {
    // 设置用户名
    setUsername(state, username) {
      state.username = username
    },
    // 设置token
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setProfile(state, profile) {
      state.profile = profile
    }

  },
  actions: {
    // 登录
    async login(context, data) {
      const res = await loginAPI(data)
      context.commit('setUsername', data.username)
      context.commit('setToken', res.data.token)
    },
    // 退出登录
    logout(context) {
      context.commit('setUsername', '')
      context.commit('setToken', '')
      removeToken()
    },
    async getProfile(ctx) {
      const { data } = await getProfileInfo()
      ctx.commit('setProfile', data)
      return data
    }
  }
}
